package image_ser

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/ctype"
	"blog_go/plugins/qiniu"
	"blog_go/utils"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"io"
	"mime/multipart"
	"path"
	"strings"
)

// 图片上传的白名单
var imagesWhitelist = []string{
	"jpg", "jpeg", "png", "gif", "webp", "ico", "tiff", "svg",
}

type FileUploadResponse struct {
	IsSuccess bool   `json:"is_success"`
	FileName  string `json:"file_name"`
	Path      string `json:"path"`
	Msg       string `json:"msg"`
}

// 文件上传
func (ImageSer) ImageUploadSer(file *multipart.FileHeader, c *gin.Context) FileUploadResponse {
	size := float64(file.Size) / float64(1024*1024)
	if size > float64(global.Conf.Upload.Size) {
		return FileUploadResponse{
			IsSuccess: false,
			FileName:  file.Filename,
			Msg:       "图片过大",
		}
	}
	split := strings.Split(file.Filename, ".")
	// 拿到后缀转成小写
	suffix := strings.ToLower(split[len(split)-1])
	listOk := utils.InList(suffix, imagesWhitelist)
	if !listOk {
		return FileUploadResponse{
			IsSuccess: false,
			FileName:  file.Filename,
			Msg:       "文件类型不在白名单",
		}
	}
	open, err := file.Open()
	if err != nil {
		logrus.Error("open file err:", err)
	}
	// 图片名字修改 只要文件没修改hash值都是一样的
	all, err := io.ReadAll(open)
	var banner models.ImageModel
	imageHash := utils.Md5(all)
	err = global.DB.Take(&banner, "hash = ?", imageHash).Error
	if err == nil {
		// 错误为空说明找到了数据
		return FileUploadResponse{
			IsSuccess: false,
			FileName:  file.Filename,
			Path:      banner.Path,
			Msg:       "图片已存在",
		}
	}
	var filePath string
	var imageType ctype.ImageType = ctype.Local
	if global.Conf.Qiniu.Enable {
		filePath, err = qiniu.UploadImage(all, file.Filename, "gvb")
		imageType = ctype.Qiniu
		if err != nil {
			logrus.Error(err)
			panic(err)
		}
	} else {
		// 保存文件 没有文件目录会自动创建
		filePath = path.Join(global.Conf.Upload.Path, file.Filename)
		// 直接这样子 会保存在项目根目录 也就是和main.go同级
		//err = c.SaveUploadedFile(file, file.Filename)
		err = c.SaveUploadedFile(file, filePath)
		if err != nil {
			logrus.Error(err)
			panic(err)
		}
	}
	global.DB.Create(&models.ImageModel{
		Path:      filePath,
		Hash:      imageHash,
		Name:      file.Filename,
		ImageType: imageType,
	})
	return FileUploadResponse{
		IsSuccess: true,
		FileName:  file.Filename,
		Path:      filePath,
		Msg:       "成功",
	}
}
